// popup.js - Kanban logic using chrome.storage.local for persistence
// 主要数据模型： { columns: [{ id, title, tasks: [{id,title,desc}] }] }

const DEFAULT_BOARD = {
    columns: [
        {
            id: genId(),
            title: "待办",
            tasks: [
                {
                    id: genId(),
                    title: "撰写项目需求文档",
                    desc: "整理产品需求，明确功能优先级和业务流程"
                },
                {
                    id: genId(),
                    title: "绘制系统架构图",
                    desc: "包含前端、后端、数据库以及外部依赖服务"
                },
                {
                    id: genId(),
                    title: "编写接口 Mock 数据",
                    desc: "为前端开发提供模拟 JSON 数据"
                },
                {
                    id: genId(),
                    title: "设计任务看板 UI",
                    desc: "包括列、任务卡片、拖拽交互等"
                },
                {
                    id: genId(),
                    title: "编写单元测试计划",
                    desc: "为关键功能准备 Jest/Mockito 测试用例"
                }
            ]
        },
        {
            id: genId(),
            title: "进行中",
            tasks: [
                {
                    id: genId(),
                    title: "开发用户注册功能",
                    desc: "实现前端表单验证与后端接口对接"
                },
                {
                    id: genId(),
                    title: "任务列表分页优化",
                    desc: "支持前端分页和后端查询优化"
                },
                {
                    id: genId(),
                    title: "Bug 修复：任务拖拽丢失",
                    desc: "修复跨列拖动时任务未保存的问题"
                },
                {
                    id: genId(),
                    title: "代码评审：登录模块",
                    desc: "审核 PR，确保密码加密和异常处理符合要求"
                }
            ]
        },
        {
            id: genId(),
            title: "已完成",
            tasks: [
                {
                    id: genId(),
                    title: "初始化 Git 仓库",
                    desc: "创建主分支并配置 .gitignore 文件"
                },
                {
                    id: genId(),
                    title: "前端项目搭建",
                    desc: "使用 Vite + Vue3 + Tailwind 初始化前端"
                },
                {
                    id: genId(),
                    title: "后端服务搭建",
                    desc: "Spring Boot 初始化，集成 MyBatis Plus"
                },
                {
                    id: genId(),
                    title: "配置 ESLint 和 Prettier",
                    desc: "统一前端代码风格"
                },
                {
                    id: genId(),
                    title: "配置 GitHub Actions",
                    desc: "支持自动构建和部署到 GitHub Pages"
                }
            ]
        }
    ]
};

const boardEl = document.getElementById('board');
const addColumnBtn = document.getElementById('add-column-btn');
const clearBtn = document.getElementById('clear-btn');

const modal = document.getElementById('modal');
const modalTitle = document.getElementById('modal-title');
const taskTitleInput = document.getElementById('task-title');
const taskDescInput = document.getElementById('task-desc');
const saveTaskBtn = document.getElementById('save-task-btn');
const cancelTaskBtn = document.getElementById('cancel-task-btn');

let state = null;
let editing = null; // { columnId, taskId } or null when adding new to specific column

// 初始化
document.addEventListener('DOMContentLoaded', init);
addColumnBtn.addEventListener('click', onAddColumn);
clearBtn.addEventListener('click', onClear);

// 模态按钮
cancelTaskBtn.addEventListener('click', closeModal);
saveTaskBtn.addEventListener('click', onSaveTask);

// 读取存储或使用默认
function init() {
    chrome.storage.local.get(['kanban_board'], res => {
        state = res.kanban_board || DEFAULT_BOARD;
        render();
    });
}

// 生成唯一 id
function genId() {
    return Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
}

// 保存到 storage
function persist() {
    chrome.storage.local.set({ kanban_board: state });
}

// 渲染整个看板
function render() {
    boardEl.innerHTML = '';
    state.columns.forEach(col => {
        const colEl = createColumnElement(col);
        boardEl.appendChild(colEl);
    });
}

// 创建列元素
function createColumnElement(column) {
    const col = document.createElement('div');
    col.className = 'column';
    col.dataset.columnId = column.id;

    const header = document.createElement('div');
    header.className = 'column-header';
    header.innerHTML = `<div class="column-title">${escapeHtml(column.title)}</div>`;
    const actions = document.createElement('div');
    actions.className = 'column-actions';
    const editBtn = document.createElement('button');
    editBtn.className = 'ghost';
    editBtn.textContent = '重命名';
    editBtn.addEventListener('click', () => {
        const newTitle = prompt('列名称', column.title);
        if (newTitle != null) {
            column.title = newTitle.trim() || column.title;
            persist(); render();
        }
    });
    const delBtn = document.createElement('button');
    delBtn.className = 'ghost';
    delBtn.textContent = '删除';
    delBtn.addEventListener('click', () => {
        if (confirm('删除此列会同时删除其所有任务，确定吗？')) {
            state.columns = state.columns.filter(c => c.id !== column.id);
            persist(); render();
        }
    });
    actions.appendChild(editBtn);
    actions.appendChild(delBtn);
    header.appendChild(actions);

    col.appendChild(header);

    // 任务容器（可拖拽）
    const tasksWrap = document.createElement('div');
    tasksWrap.className = 'tasks-wrap';
    tasksWrap.dataset.columnId = column.id;

    if (column.tasks.length === 0) {
        const p = document.createElement('div');
        p.className = 'placeholder';
        p.textContent = '暂无任务，拖拽或点击添加';
        tasksWrap.appendChild(p);
    } else {
        column.tasks.forEach(task => {
            const card = createTaskElement(column.id, task);
            tasksWrap.appendChild(card);
        });
    }

    // 允许拖拽：设置拖放监听
    tasksWrap.addEventListener('dragover', e => {
        e.preventDefault();
        const afterEl = getDragAfterElement(tasksWrap, e.clientY);
        const dragging = document.querySelector('.dragging');
        if (!dragging) return;
        if (afterEl == null) tasksWrap.appendChild(dragging);
        else tasksWrap.insertBefore(dragging, afterEl);
    });
    tasksWrap.addEventListener('drop', e => {
        e.preventDefault();
        // 在 drop 完成后，重新构建 state
        rebuildStateFromDOM();
        persist();
        render(); // 重新渲染以清理拖拽样式
    });

    col.appendChild(tasksWrap);

    const addCardBtn = document.createElement('button');
    addCardBtn.className = 'add-card';
    addCardBtn.textContent = '+ 添加任务';
    addCardBtn.addEventListener('click', () => openModalForNew(column.id));
    col.appendChild(addCardBtn);

    return col;
}

// 创建任务卡片
function createTaskElement(columnId, task) {
    const card = document.createElement('div');
    card.className = 'card';
    card.draggable = true;
    card.dataset.taskId = task.id;
    card.dataset.columnId = columnId;

    card.innerHTML = `
    <div class="card-title">${escapeHtml(task.title)}</div>
    ${task.desc ? `<div class="card-desc">${escapeHtml(task.desc)}</div>` : ''}
    <div style="display:flex;gap:6px;margin-top:8px;justify-content:flex-end">
      <button class="ghost edit-card">编辑</button>
      <button class="ghost delete-card">删除</button>
    </div>
  `;

    // 拖拽事件
    card.addEventListener('dragstart', (e) => {
        card.classList.add('dragging');
        // 传递数据
        e.dataTransfer.setData('text/plain', JSON.stringify({ taskId: task.id, columnId }));
        // 小延迟：fix 在 chrome popup 中拖拽行为
        setTimeout(() => card.style.display = 'block', 0);
    });
    card.addEventListener('dragend', () => {
        card.classList.remove('dragging');
    });

    // 编辑删除事件
    card.querySelector('.edit-card').addEventListener('click', () => openModalForEdit(columnId, task.id));
    card.querySelector('.delete-card').addEventListener('click', () => {
        if (confirm('删除任务？')) {
            const col = state.columns.find(c => c.id === columnId);
            if (col) col.tasks = col.tasks.filter(t => t.id !== task.id);
            persist(); render();
        }
    });

    return card;
}

// 打开新增任务模态
function openModalForNew(columnId) {
    editing = { columnId, taskId: null };
    modalTitle.textContent = '新增任务';
    taskTitleInput.value = '';
    taskDescInput.value = '';
    modal.classList.remove('hidden');
    taskTitleInput.focus();
}

// 打开编辑模态
function openModalForEdit(columnId, taskId) {
    editing = { columnId, taskId };
    const col = state.columns.find(c => c.id === columnId);
    const task = col.tasks.find(t => t.id === taskId);
    modalTitle.textContent = '编辑任务';
    taskTitleInput.value = task.title;
    taskDescInput.value = task.desc || '';
    modal.classList.remove('hidden');
    taskTitleInput.focus();
}

function closeModal() {
    modal.classList.add('hidden');
    editing = null;
}

// 保存任务（新增或编辑）
function onSaveTask() {
    const title = taskTitleInput.value.trim();
    const desc = taskDescInput.value.trim();
    if (!title) {
        alert('请填写标题');
        return;
    }
    const col = state.columns.find(c => c.id === editing.columnId);
    if (!col) {
        alert('目标列不存在');
        closeModal();
        return;
    }
    if (editing.taskId) {
        // 编辑
        const task = col.tasks.find(t => t.id === editing.taskId);
        if (task) {
            task.title = title;
            task.desc = desc;
        }
    } else {
        // 新增
        col.tasks.unshift({ id: genId(), title, desc });
    }
    persist();
    closeModal();
    render();
}

// 添加列
function onAddColumn() {
    const title = prompt('列名称', '新列');
    if (title == null) return;
    state.columns.push({ id: genId(), title: title.trim() || '新列', tasks: [] });
    persist(); render();
}

// 清空数据
function onClear() {
    if (confirm('清空所有数据？此操作不可撤销')) {
        state = JSON.parse(JSON.stringify(DEFAULT_BOARD));
        persist(); render();
    }
}

// 通过 DOM 重建 state（用于拖拽后更新列/任务顺序）
function rebuildStateFromDOM() {
    const newColumns = [];
    const columnEls = Array.from(document.querySelectorAll('.column'));
    columnEls.forEach(colEl => {
        const colId = colEl.dataset.columnId;
        const colModel = state.columns.find(c => c.id === colId) || { id: colId, title: colEl.querySelector('.column-title')?.textContent || '新列', tasks: [] };
        // collect tasks in this column DOM order
        const taskEls = Array.from(colEl.querySelectorAll('.card'));
        const tasks = taskEls.map(tEl => {
            const taskId = tEl.dataset.taskId;
            // find original task
            for (const c of state.columns) {
                const found = c.tasks.find(x => x.id === taskId);
                if (found) return { id: found.id, title: found.title, desc: found.desc };
            }
            // fallback: create minimal
            return { id: taskId || genId(), title: tEl.querySelector('.card-title')?.textContent || '没有标题', desc: tEl.querySelector('.card-desc')?.textContent || '' };
        });
        newColumns.push({ id: colId, title: colModel.title, tasks });
    });
    state.columns = newColumns;
}

// 获取拖拽时在列中当前位置的元素
function getDragAfterElement(container, y) {
    const draggableElements = [...container.querySelectorAll('.card:not(.dragging)')];
    return draggableElements.reduce((closest, child) => {
        const box = child.getBoundingClientRect();
        const offset = y - box.top - box.height / 2;
        if (offset < 0 && offset > closest.offset) {
            return { offset: offset, element: child };
        } else {
            return closest;
        }
    }, { offset: Number.NEGATIVE_INFINITY }).element;
}

// 简单转义防 XSS
function escapeHtml(s) {
    if (!s) return '';
    return s.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;');
}